var Q = require('q'),
    operationController = require('../../../CBO/server/controllers/Operation.server.controller'),
    barcodeMasterController = require('../../../Barcode/server/controllers/BarcodeMaster.server.controller'),
    bizRecordController = require('../../../Barcode/server/controllers/BizRecord.server.controller'),
    qcRecordController = require('../../../QC/server/controllers/QCRecord.server.controller'),
    workController = require('../../../CBO/server/controllers/Work.server.controller'),
    enumController = require('../../../QC/server/controllers/Enum.server.controller');
//通过Barcode获取条码主档信息
exports.getBarcodeData = function (req, res) {
    var parameter = req.body.Parameter,
        Barcode = parameter.Barcode;
    barcodeMasterController.findBarcodeMasterAllData(Barcode, function (err, result) {
        // console.log("getBarcodeData-------------"+result);
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (result == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码失败';
                newErr.message = '未找到对应的条码！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                res.json({
                    Data: result,
                    Error: null
                });
            }
        }
    });
};

//更新流水的采集时间、用户信息，删除原品质记录并重新创建。更新主档的用户
exports.updateBadData = function (req, res) {
    var parameter = req.body.Parameter,
        UserId = parameter.User,
        BarcodeId = parameter.BarcodeId,
        Barcode = parameter.Barcode,
        badRecords = parameter.badRecords,
        BizRecordId = parameter.BizRecord;

    var dateNow = Date.now();
    var updatebizRecord = {
        Users: [UserId],
        CollectDateTime: dateNow
    };

    //更新流水采集时间，用户
    bizRecordController.updateBizRecordByValue(BizRecordId, updatebizRecord, function (err, record) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        }
        else {
            //删除QC记录
            qcRecordController.deleteQCRecords(BizRecordId, function (err, result) {
                if (err) {
                    res.json({
                        Data: null,
                        Error: err
                    });
                }
                else {
                    //添加QC记录
                    qcRecordController.addQCRecords(BizRecordId, badRecords, function (err, result) {
                        if (err) {
                            res.json({
                                Data: null,
                                Error: err
                            });
                        }
                        //更新主档信息
                        barcodeMasterController.updateByValue(Barcode, {Users: [UserId]}, function (err, result) {
                            if (err) {
                                res.json({
                                    Data: null,
                                    Error: err
                                });
                            }
                            else {
                                if (result.ok === 1) {
                                    res.json({
                                        Data: true,
                                        Error: null
                                    });
                                }
                            }

                        });
                    });
                }
            });
        }

    });
};


//通过Barcode获取检验作业条码主档信息
exports.getBarcodeDefectData = function (req, res) {
    var parameter = req.body.Parameter,
        BarcodeId = parameter.BarcodeId,
        Work = parameter.Work;

    var returnData = [];
    
    barcodeMasterController.findBarcodeMasterByBarcodeMaster(BarcodeId, function(err,result){
       if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (result == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码失败';
                newErr.message = '未找到对应的条码！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                console.log('result.BizRecord-----------'+result.BizRecord);
                qcRecordController.findAllQCRecords(result.BizRecord, function (err, results) {
                    if (err) {
                        res.json({
                            Data: null,
                            Error: err
                        });
                    }
                    else {
                        if (results == null) {
                            var newErr = new Error();
                            newErr.leval = 9;
                            newErr.title = '查询品质记录失败';
                            newErr.message = '未找到对应的品质记录！';
                            res.json({
                                Data: null,
                                Error: newErr
                            });
                        }
                        else {
                            var BadTypeOptions = [];
                            var BadPositionOptions = [];
                            var qcRecords = results;

                            //查找所有的不良类型
                            enumController.findAllExtendEnum("BadType", function (err, result) {
                                if (err) {
                                    res.json({
                                        Data: null,
                                        Error: err
                                    });
                                }
                                else {
                                    if (result == null) {
                                        var newErr = new Error();
                                        newErr.leval = 9;
                                        newErr.title = '查询不良类型失败';
                                        newErr.message = '未找到所有的不良类型！';
                                        res.json({
                                            Data: null,
                                            Error: newErr
                                        });
                                    }
                                    else {
                                        BadTypeOptions = result.Options;
                                        //查找所有的不良类型
                                        enumController.findAllExtendEnum("BadPosition", function (err, result) {
                                            if (err) {
                                                res.json({
                                                    Data: null,
                                                    Error: err
                                                });
                                            }
                                            else {
                                                if (result == null) {
                                                    var newErr = new Error();
                                                    newErr.leval = 9;
                                                    newErr.title = '查询不良位置失败';
                                                    newErr.message = '未找到所有的不良位置！';
                                                    res.json({
                                                        Data: null,
                                                        Error: newErr
                                                    });
                                                }
                                                else {
                                                    BadPositionOptions = result.Options;
                                                    // var promises = [];
                                                    // results.forEach(function (result) {
                                                    //     promises.push(queryBadTypeAndBadPosition(result));   
                                                    // });
                                                    qcRecords.forEach(function (qcRecord) {
                                                        for (var i = 0; i < BadTypeOptions.length; i++) {
                                                            if (BadTypeOptions[i].Value === qcRecord.BadType) {
                                                                for (var j = 0; j < BadPositionOptions.length; j++) {
                                                                    if (BadPositionOptions[j].Value === qcRecord.BadPosition) {
                                                                        returnData.push({
                                                                            BadType: BadTypeOptions[i].Name,
                                                                            BadTypeValue: BadTypeOptions[i].Value,
                                                                            BadPosition: BadPositionOptions[j].Name,
                                                                            BadPositionValue: BadPositionOptions[j].Value,
                                                                            Description: qcRecord.Description,
                                                                            BizRecord: qcRecord.BizRecord
                                                                        })
                                                                    }
                                                                }
                                                                ;

                                                            }

                                                        }
                                                        ;
                                                    });
                                                    res.json({
                                                        Data: returnData,
                                                        Error: null
                                                    });

                                                }
                                            }

                                        });

                                    }
                                }

                            });


                        }
                    }

                });
            }
        }
    });

    // bizRecordController.findAllByBarcodeMasterAndWork(BarcodeId, Work, function (err, result) {
    //     if (err) {
    //         res.json({
    //             Data: null,
    //             Error: err
    //         });
    //     }
    //     else {
    //         if (result == null) {
    //             var newErr = new Error();
    //             newErr.leval = 9;
    //             newErr.title = '查询条码流水失败';
    //             newErr.message = '未找到对应的条码流水！';
    //             res.json({
    //                 Data: null,
    //                 Error: newErr
    //             });
    //         }
    //         else {
    //             qcRecordController.findAllQCRecords(result[0]._id, function (err, results) {
    //                 if (err) {
    //                     res.json({
    //                         Data: null,
    //                         Error: err
    //                     });
    //                 }
    //                 else {
    //                     if (results == null) {
    //                         var newErr = new Error();
    //                         newErr.leval = 9;
    //                         newErr.title = '查询品质记录失败';
    //                         newErr.message = '未找到对应的品质记录！';
    //                         res.json({
    //                             Data: null,
    //                             Error: newErr
    //                         });
    //                     }
    //                     else {
    //                         var BadTypeOptions = [];
    //                         var BadPositionOptions = [];
    //                         var qcRecords = results;

    //                         //查找所有的不良类型
    //                         enumController.findAllExtendEnum("BadType", function (err, result) {
    //                             if (err) {
    //                                 res.json({
    //                                     Data: null,
    //                                     Error: err
    //                                 });
    //                             }
    //                             else {
    //                                 if (result == null) {
    //                                     var newErr = new Error();
    //                                     newErr.leval = 9;
    //                                     newErr.title = '查询不良类型失败';
    //                                     newErr.message = '未找到所有的不良类型！';
    //                                     res.json({
    //                                         Data: null,
    //                                         Error: newErr
    //                                     });
    //                                 }
    //                                 else {
    //                                     BadTypeOptions = result.Options;
    //                                     //查找所有的不良类型
    //                                     enumController.findAllExtendEnum("BadPosition", function (err, result) {
    //                                         if (err) {
    //                                             res.json({
    //                                                 Data: null,
    //                                                 Error: err
    //                                             });
    //                                         }
    //                                         else {
    //                                             if (result == null) {
    //                                                 var newErr = new Error();
    //                                                 newErr.leval = 9;
    //                                                 newErr.title = '查询不良位置失败';
    //                                                 newErr.message = '未找到所有的不良位置！';
    //                                                 res.json({
    //                                                     Data: null,
    //                                                     Error: newErr
    //                                                 });
    //                                             }
    //                                             else {
    //                                                 BadPositionOptions = result.Options;
    //                                                 // var promises = [];
    //                                                 // results.forEach(function (result) {
    //                                                 //     promises.push(queryBadTypeAndBadPosition(result));   
    //                                                 // });
    //                                                 qcRecords.forEach(function (qcRecord) {
    //                                                     for (var i = 0; i < BadTypeOptions.length; i++) {
    //                                                         if (BadTypeOptions[i].Value === qcRecord.BadType) {
    //                                                             for (var j = 0; j < BadPositionOptions.length; j++) {
    //                                                                 if (BadPositionOptions[j].Value === qcRecord.BadPosition) {
    //                                                                     returnData.push({
    //                                                                         BadType: BadTypeOptions[i].Name,
    //                                                                         BadTypeValue: BadTypeOptions[i].Value,
    //                                                                         BadPosition: BadPositionOptions[j].Name,
    //                                                                         BadPositionValue: BadPositionOptions[j].Value,
    //                                                                         Description: qcRecord.Description,
    //                                                                         BizRecord: qcRecord.BizRecord
    //                                                                     })
    //                                                                 }
    //                                                             }
    //                                                             ;

    //                                                         }

    //                                                     }
    //                                                     ;
    //                                                 });
    //                                                 res.json({
    //                                                     Data: returnData,
    //                                                     Error: null
    //                                                 });

    //                                             }
    //                                         }

    //                                     });

    //                                 }
    //                             }

    //                         });


    //                     }
    //                 }

    //             });
    //         }
    //     }
    // });
};


// function queryBadTypeAndBadPosition (qcRecord) {
//     var deferred = Q.defer();

//     enumController.findAllExtendEnum("BadType", function (err, result) {
//         if (err) {
//             deferred.reject(err);
//             return;
//         }
//         if (result.QCNorm) {
//             qcRecord.QCNorm = result.QCNorm._id;
//         } 
//         deferred.resolve();            
//     });  

//     return deferred.promise;
// }

//检验作业提交
exports.submitCheckWork = function (req, res) {
    var parameter = req.body.Parameter,
        barcode = parameter.Barcode,
        barcodeMaster = parameter.BarcodeMaster,
        ItemMaster = parameter.ItemMaster,
        Terminal = parameter.Terminal,
        TerminalName = parameter.TerminalName,
        Work = parameter.Work,
        WorkName = parameter.WorkName,
        WorkLocation = parameter.WorkLocation,
        WorkLocationName = parameter.WorkLocationName,
        userId = parameter.UserID,
    //0: 合格 1:不合格
        QCStatus = parameter.QCStatus,
        badRecords = parameter.badRecords

    var dateNow = Date.now(),
        bizRecord = {
            CollectDateTime: dateNow,
            Users: [userId],
            BusinessStatus: 1,//业务状态：完成
            QCType: 0,//质检类型：全检
            QCUser: userId,
            QCDateTime: dateNow,
            QCStatus: QCStatus
        };

    //根据物料和作业查找工序
    operationController.findByItemMasterAndWork(ItemMaster, Work, function (err, operationRecord) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        }
        else {
            if (operationRecord == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询工序失败';
                newErr.message = '该物料没有找到对应作业的工序！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            }
            else {
                // console.log("工序-------------"+operationRecord);
                bizRecord.BarcodeMaster = barcodeMaster;
                bizRecord.Work = Work;
                bizRecord.WorkName = WorkName;
                bizRecord.WorkLocation = WorkLocation;
                bizRecord.WorkLocationName = WorkLocationName;
                bizRecord.Terminal = Terminal;
                bizRecord.TerminalName = TerminalName;
                bizRecord.Operation = operationRecord._id;
                bizRecord.OperationName = operationRecord.Name;

                writebizRecord(barcode, bizRecord, badRecords).then(function (result) {
                    res.json(result);
                }, function (err) {
                    res.json(err);
                });
            }
        }
    });
};


function writebizRecord(barcode, bizRecord, badRecords) {
    var deferred = Q.defer();
    //添加流水信息
    bizRecordController.insert(bizRecord, function (err, record) {
        if (err) {
            deferred.reject(err);
            return;
        }
        var updateRecord = {
            Users: bizRecord.Users,
            BusinessStatus: bizRecord.BusinessStatus,
            QCStatus: bizRecord.QCStatus,
            BizRecord: record._id,
            Work: bizRecord.Work,
            WorkName: bizRecord.WorkName,
            WorkLocation: bizRecord.WorkLocation,
            WorkLocationName: bizRecord.WorkLocationName,
            Terminal: bizRecord.Terminal,
            TerminalName: bizRecord.TerminalName,
            Operation: bizRecord.Operation,
            OperationName: bizRecord.OperationName
        };
        //添加QC记录
        qcRecordController.addQCRecords(record._id, badRecords, function (err, result) {
            if (err) {
                deferred.reject(err);
                return;
            }
            //更新主档信息
            barcodeMasterController.updateByValue(barcode, updateRecord, function (err, result) {
                if (err) {
                    deferred.reject(err);
                    return;
                }
                if (result.ok === 1) {
                    deferred.resolve({
                        Data: true,
                        Error: null
                    });
                }

            });
        });
    });
    return deferred.promise;
}
